import { HttpException, HttpStatus, Injectable, Query } from '@nestjs/common';
import { CreateRoleDto, DeleteRoleDto, FindManyRoleDto, UpdateRoleDto } from '../dto/role.dto';
import { PrismaService } from 'src/module/prisma/prisma.service';

@Injectable()
export class RoleService {
    constructor(private readonly prismaService: PrismaService) { }

    async create(cd: CreateRoleDto) {
        const role = await this.prismaService.role.findUnique({
            where: { name: cd.name }
        })
        if (role) {
            throw new HttpException('角色已存在', HttpStatus.BAD_REQUEST);
        }

        return this.prismaService.role.create({ data: { name: cd.name } })
    }

    delete(dd: DeleteRoleDto) {
        try {
            return this.prismaService.role.delete({ where: { id: dd.id } })
        } catch (error) {
            throw new HttpException('角色删除失败', HttpStatus.BAD_REQUEST);
        }
    }

    async update(ud: UpdateRoleDto) {

        const role = await this.prismaService.role.findUnique({
            where: { name: ud.newName, NOT: { id: ud.id } }
        })
        if (role) {
            throw new HttpException('角色已存在', HttpStatus.BAD_REQUEST);
        }
        try {
            return this.prismaService.role.update({
                where: { id: ud.id },
                data: {
                    name: ud.newName,
                    permissions: {
                        deleteMany: {},
                        create: ud.permissions.map((pid: any) => ({
                            permissionId: pid.id
                        }))
                    }
                }
            })
        } catch (error) {
            throw new HttpException('角色编辑失败', HttpStatus.BAD_REQUEST);
        }
    }

    async findMany(fmd: FindManyRoleDto) {
        try {
            const res = await this.prismaService.role.findMany({
                include: {
                    permissions: {
                        include: {
                            permission: true
                        }
                    }
                },
                skip: fmd.page ? ((fmd.page - 1) * fmd.limit) : 0,
                take: fmd.limit,
                orderBy: { [fmd.orderBy]: fmd.orderDirection },
            });
            const perRes = res.map((item) => {
                const { permissions } = item
                return {
                    ...item,
                    permissions: permissions.map((rp) => rp.permission?.code).filter(Boolean)
                }
            })
            return perRes;

        } catch (error) {
            throw new HttpException('获取角色列表失败', HttpStatus.BAD_REQUEST)
        }
    }
}
